import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';
import 'package:video_ducafecat_flutter_v3/pages/index.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  @override
  bool get wantKeepAlive => true;

  // 退出请求时间
  DateTime? currentBackPressTime;

  // 返回键退出
  bool closeOnConfirm() {
    DateTime now = DateTime.now();
    // 物理键，两次间隔大于4秒, 退出请求无效
    if (currentBackPressTime == null ||
        now.difference(currentBackPressTime!) > const Duration(seconds: 4)) {
      currentBackPressTime = now;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          behavior: SnackBarBehavior.floating,
          content: Center(child: Text('Press again to close the app.')),
          duration: Duration(seconds: 4),
        ),
      );
      return false;
    }

    // 退出请求有效
    currentBackPressTime = null;
    return true;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    ConfigService.to.setAppLifecycle(state);
  }

// 主视图
  Widget _buildView(MainController controller) {
    /// PopScope
    /// ios 是顶部导航返回按钮
    /// android 是系统返回按钮
    return PopScope(
      // 允许
      canPop: false,

      // pop请求
      onPopInvoked: (bool didPop) async {
        if (didPop) {
          return;
        }
        if (closeOnConfirm()) {
          // 系统级别导航栈 退出程序
          SystemNavigator.pop();
        }
      },
      child: Scaffold(
        extendBody: true,
        resizeToAvoidBottomInset: false,

        // 顶部导航
        // appBar: mainAppBarWidget(),

        // 导航栏
        bottomNavigationBar: GetBuilder<MainController>(
          id: 'navigation',
          builder: (controller) {
            return Obx(() => BuildNavigation(
                  currentIndex: controller.currentIndex,
                  items: [
                    // 首页
                    NavigationItemModel(
                      label: LocaleKeys.tabBarHome.tr,
                      iconData: Icons.home_outlined,
                    ),
                    // 博客
                    NavigationItemModel(
                      label: LocaleKeys.tabBarBlog.tr,
                      iconData: Icons.rss_feed_outlined,
                      count: 0,
                    ),
                    // 聊天
                    NavigationItemModel(
                      label: LocaleKeys.tabBarMessage.tr,
                      iconData: Icons.chat_outlined,
                      count: IMService.to.totalUnreadCount.value,
                    ),
                    // 我的
                    NavigationItemModel(
                      label: LocaleKeys.tabBarProfile.tr,
                      iconData: Icons.person_outline_outlined,
                    ),
                  ],
                  onTap: controller.onJumpToPage, // 切换tab事件
                ));
          },
        ),

        // 内容页
        body: PageView(
          physics: const NeverScrollableScrollPhysics(),
          controller: controller.pageController,
          onPageChanged: controller.onIndexChanged,
          children: const [
            CourseIndexPage(),
            BlogIndexPage(),
            ChatIndexPage(),
            MyIndexPage(),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<MainController>(
      // init: MainController(),
      // init: Get.find<MainController>(),
      id: "main",
      builder: (controller) => _buildView(controller),
    );
  }
}
